import React, { useState } from 'react';
import {
  DatePicker,
  Button,
  Input,
  Table,
  Form,
  Select,
  message,
  Row,
  Col,
} from 'antd';
import { Link } from 'umi';
import request from '@/http';

const { RangePicker } = DatePicker;
const { Option } = Select;

export default () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(true);
  function onChange(value: any, dateString: any) {
    console.log('Selected Time: ', value);
    console.log('Formatted Selected Time: ', dateString);
  }

  function onOk(value: any) {
    console.log('onOk: ', value);
  }

  const [formObject] = Form.useForm();
  const [dataSource, setDataSource] = React.useState<any[]>([]);
  const [pagination, setPagination] = React.useState({
    current: 1,
    total: 1,
    pageSize: 5,
    showSizeChanger: true,
    pageSizeOptions: ['5', '10', '20', '50'],
    showQuickJumper: true,
  });
  const loadDataSource = async (
    userParams: any,
    pageValue: any,
    pageSize: any,
  ) => {
    const result: any = await request.get(
      '/api/teacher/attendance/getAttendance',
      {
        params: {
          ...userParams,
          pageNum: pageValue,
          pageSize: pageSize,
        },
      },
    );
    // console.log(result);

    if (result.success) {
      const data: any = result.data.records.map((user: any) => ({
        key: `user_${user.id}`,
        id: user.id,
        attendanceType: user.attendanceType,
        className: user.className,
        collegesName: user.collegesName,
        courseName: user.courseName,
        dutyTeacher: user.dutyTeacher,
        gradeName: user.gradeName,
        leaveId: user.leaveId,
        majorName: user.majorName,
        projectDate: user.projectDate,
        realEndTime: user.realEndTime ? user.realEndTime : '/',
        realStartTime: user.realStartTime ? user.realStartTime : '/',
        signInTime: user.signInTime,
        signOutTime: user.signOutTime,
        studentName: user.studentName,
        teamName: user.teamName,
        trainTeacher: user.trainTeacher,
        userNo: user.userNo,
      }));
      setDataSource(data);
      setLoading(false);
      const newPageObject = {
        ...pagination,
        current: pageValue,
        pageSize: pageSize,
        total: result.records, //总条数 分页
      };

      console.log(result.records);
      setPagination(newPageObject);
      // console.log(data)
    }
  };

  const cCollege = localStorage.getItem('collegeName');
  if (cCollege != null) {
    var cCollegeData = JSON.parse(cCollege);
  }
  const cGrade = localStorage.getItem('gradeName');
  if (cGrade != null) {
    var cGradeData = JSON.parse(cGrade);
  }
  let cClass = localStorage.getItem('classname');
  if (cClass != null) {
    var cClassData = JSON.parse(cClass);
  }
  let cMajor = localStorage.getItem('major');
  if (cMajor != null) {
    var cMajorData = JSON.parse(cMajor);
  }
  let cTeacher = localStorage.getItem('teacher');
  if (cTeacher != null) {
    var cTeacherData = JSON.parse(cTeacher);
  }
  let cHeadTeacher = localStorage.getItem('headTeacher');
  if (cHeadTeacher != null) {
    var cHeadTeacherData = JSON.parse(cHeadTeacher);
  }

  //搜索
  const searchOnClick = async () => {
    // console.log(formObject.getFieldsValue());
    const data = await formObject.validateFields();
    var dataStr = '';
    var ds = {
      ...data,
    };
    //console.log(data);
    for (var n in ds) {
      if (dataStr != '') dataStr += '&';
      dataStr += encodeURIComponent(n) + '=' + encodeURIComponent(ds[n]);
    }

    await loadDataSource(data, 1, pagination.pageSize);
  };

  /*下拉菜单*/
  const [classInfo, setClassInfo] = useState([]); //班级钩子
  const [college, setCollege] = useState([]); //院系钩子
  const [course, setCourse] = useState([]); //课程钩子
  const [grade, setGrade] = useState([]); //年级钩子
  const [major, setMajor] = useState([]); //专业钩子
  //班级请求
  const loadSelectClass = async () => {
    const result: any = await request.post(
      '/api/common_module/a_t_s/getClassInfo',
    );
    if (result.success) {
      setClassInfo(result.data);
    }
  };
  //院系请求
  const loadSelectCollege = async () => {
    const result: any = await request.post(
      '/api/common_module/a_t_s/getCollege',
    );
    if (result.success) {
      setCollege(result.data);
    }
  };
  //课程请求
  const loadSelectCourse = async () => {
    const result: any = await request.post(
      '/api/common_module/a_t_s/getCourse',
    );
    if (result.success) {
      setCourse(result.data);
    }
  };

  //年级请求
  const loadSelectGrade = async () => {
    const result: any = await request.post('/api/common_module/a_t_s/getGrade');
    if (result.success) {
      setGrade(result.data);
    }
  };

  //专业请求
  const loadSelectMajor = async () => {
    const result: any = await request.post('/api/common_module/a_t_s/getMajor');
    if (result.success) {
      setMajor(result.data);
    }
  };

  //生命周期函数
  React.useEffect(() => {
    loadSelectClass();
    loadSelectCollege();
    loadSelectCourse();
    loadSelectGrade();
    loadSelectMajor();
    loadDataSource(null, 1, pagination.pageSize).finally();
  }, []);

  //换页
  const pageOnChange = async (page: any) => {
    await loadDataSource(
      formObject.getFieldsValue(),
      page.current,
      page.pageSize,
    );
  };

  const formItemLayout = {
    labelCol: {
      span: 7,
    },
    wrapperCol: {
      span: 24,
    },
  };

  const onFinish = (values: any) => {
    console.log(values);
    const data = {
      attendanceType: values.status,
      className: values.className,
      collegesName: values.collegeName,
      courseName: values.courseName,
      gradeName: values.gradeName,
      majorName: values.majorName,
      studentName: values.responseTeacherName,
      userNo: values.stuNumber,
      startDate: values.date ? values.date[0].format('yyyy-MM-DD') : '',
      endDate: values.date ? values.date[1].format('yyyy-MM-DD') : '',
    };
    loadDataSource(data, 1, 10);
  };
  return (
    <>
      <Form form={form} {...formItemLayout} onFinish={onFinish}>
        <Row gutter={24} wrap={false} style={{ width: '90%' }}>
          <Col span={8}>
            <Form.Item label="日期" name="date">
              <RangePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="院系" name="collegeName">
              <Select style={{ width: '100%' }} placeholder="请选择">
                {college.map((item: any) => {
                  return (
                    <Option value={item.collegeName}>{item.collegeName}</Option>
                  );
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="专业" name="majorName">
              <Select style={{ width: '100%' }} placeholder="请选择">
                {major.map((item: any) => {
                  return (
                    <Option value={item.majorName}>{item.majorName}</Option>
                  );
                })}
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24} wrap={false} style={{ width: '90%' }}>
          <Col span={8}>
            <Form.Item label="年级" name="gradeName">
              <Select style={{ width: '100%' }} placeholder="请选择">
                {grade.map((item: any) => {
                  return (
                    <Option value={item.gradeName}>{item.gradeName}</Option>
                  );
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="班级" name="className">
              <Select style={{ width: '100%' }} placeholder="请选择">
                {classInfo.map((item: any) => {
                  return (
                    <Option value={item.className}>{item.className}</Option>
                  );
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="项目名称" name="courseName">
              <Select style={{ width: '100%' }} placeholder="请选择">
                {course.map((item: any) => {
                  return (
                    <Option value={item.courseName}>{item.courseName}</Option>
                  );
                })}
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24} wrap={false} style={{ width: '90%' }}>
          <Col span={8}>
            <Form.Item label="学号" name="stuNumber">
              <Input style={{ width: '100%' }} placeholder="请输入..." />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="学员姓名" name="responseTeacherName">
              <Input style={{ width: '100%' }} placeholder="请输入..." />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="考勤情况" name="status">
              <Select style={{ width: '100%' }} placeholder="请选择">
                <Option value="0">出勤</Option>
                <Option value="1">迟到</Option>
                <Option value="2">早退</Option>
                <Option value="3">缺勤</Option>
                <Option value="4">请假</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24} wrap={false} style={{ width: '90%' }}>
          <Col span={8}>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button
                style={{ margin: '0 8px' }}
                onClick={() => {
                  form.resetFields();
                  loadDataSource(null, 1, pagination.pageSize);
                }}
              >
                重置
              </Button>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <Table
        scroll={{ x: 2500 }}
        loading={loading}
        columns={[
          {
            title: '日期',
            dataIndex: 'projectDate',
            key: 'projectDate',
            align: 'center',
          },
          {
            title: '小组',
            dataIndex: 'teamName',
            key: 'teamName',
            align: 'center',
          },
          {
            title: '院系',
            dataIndex: 'collegesName',
            key: 'collegesName',
            align: 'center',
          },
          {
            title: '专业',
            dataIndex: 'majorName',
            key: 'majorName',
            align: 'center',
          },
          {
            title: '年级',
            dataIndex: 'gradeName',
            key: 'gradeName',
            align: 'center',
          },
          {
            title: '班级',
            dataIndex: 'className',
            key: 'className',
            align: 'center',
          },
          {
            title: '项目名称',
            dataIndex: 'courseName',
            key: 'courseName',
            align: 'center',
          },
          {
            title: '实训老师',
            dataIndex: 'trainTeacher',
            key: 'trainTeacher',
            align: 'center',
          },
          {
            title: '责任老师',
            dataIndex: 'dutyTeacher',
            key: 'dutyTeacher',
            align: 'center',
          },
          {
            title: '姓名',
            dataIndex: 'studentName',
            key: 'studentName',
            align: 'center',
          },
          {
            title: '学号',
            dataIndex: 'userNo',
            key: 'userNo',
            align: 'center',
          },
          {
            title: '考勤情况',
            dataIndex: 'attendanceType',
            key: 'attendanceType',
            align: 'center',
          },
          {
            title: '应签到',
            dataIndex: 'signInTime',
            key: 'signInTime',
            align: 'center',
          },
          {
            title: '实签到',
            dataIndex: 'realStartTime',
            key: 'realStartTime',
            align: 'center',
          },
          {
            title: '应签退',
            dataIndex: 'signOutTime',
            key: 'signOutTime',
            align: 'center',
          },
          {
            title: '实签退',
            dataIndex: 'realEndTime',
            key: 'realEndTime',
            align: 'center',
          },

          {
            title: '操作',
            key: 'action',
            align: 'center',
            render: (row: any) => (
              <>
                <Link to="/global/askForLeave/particulars">
                  <Button type="link">查看请假原因</Button>
                </Link>
              </>
            ),
          },
        ]}
        dataSource={dataSource}
        pagination={pagination}
        onChange={pageOnChange}
        // tableLayout="fixed"
        bordered
      />
    </>
  );
};
